import SingleUpload from '@/components/SingleUpload';
import type { RoleRecord } from '@/DatabaseType/Role';
import type { UserRecord } from '@/DatabaseType/User';
import { getRoleList } from '@/services/role';
import {
  addUser,
  deleteUser,
  getUser,
  getUserList,
  updateUser,
} from '@/services/user';
import {
  DEFAULT_REQUIRED_RULE,
  IMAGE_FALL_BACK,
  MODAL_TITLE_MAP,
} from '@/constant';
import { ResponseCode } from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import {
  Button,
  Form,
  Image,
  Input,
  message,
  Modal,
  notification,
  Popconfirm,
  Select,
} from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import { FormLayout } from '../Common/config';

const UserManagement = () => {
  const { initialState, refresh: fetchUserInfo } = useModel('@@initialState');
  const currentUser = initialState?.currentUser as UserRecord;

  const actionRef = useRef<ActionType>();
  const [modalConfig, setModalConfig] = useState<{
    visible: boolean;
    type: 'edit' | 'view' | 'add';
    userId?: number;
  }>({
    visible: false,
    type: 'add',
  });
  const [formInstance] = Form.useForm();
  const [operateLoading, setOperateLoadingLoading] = useState(false);
  const [roleList, setRoleList] = useState<RoleRecord[]>([]);

  const roleListOptions = useMemo(() => {
    return roleList.map((item) => ({
      ...item,
      value: item.id,
      label: item.name,
    }));
  }, [roleList]);

  const columns: ProColumns<UserRecord>[] = [
    {
      title: '主键',
      dataIndex: 'id',
      width: 75,
      align: 'center',
    },
    {
      title: '账号',
      dataIndex: 'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
    },
    {
      title: '头像',
      dataIndex: 'avatarImage',
      render(text, { avatarImage }) {
        return (
          <Image
            style={{ objectFit: 'contain' }}
            width={60}
            height={60}
            src={avatarImage || IMAGE_FALL_BACK}
            alt="avatarImage"
            fallback={IMAGE_FALL_BACK}
          />
        );
      },
      hideInSearch: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      render: (text, { id: userId }) => [
        <a
          key="view-detail"
          onClick={() => {
            // 打开弹窗
            setModalConfig((config) => ({
              ...config,
              visible: true,
              type: 'view',
              userId,
            }));
            // 获取详情写入表单
            viewDetail(userId);
          }}
        >
          查看
        </a>,
        <a
          key="edit-detail"
          onClick={() => {
            // 打开弹窗
            setModalConfig((config) => ({
              ...config,
              visible: true,
              type: 'edit',
              userId,
            }));
            // 获取详情写入表单
            viewDetail(userId);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="delete-detail"
          title="确认删除该记录吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => sureDeleteUser(userId)}
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  // 确认删除角色
  async function sureDeleteUser(userId: number) {
    try {
      const { code, message: msg } = await deleteUser(userId);
      if (code === ResponseCode.Success) {
        notification.success({ message: '删除成功' });
        actionRef.current?.reload();
      } else {
        notification.error({ message: msg || '删除失败' });
      }
    } catch (error: any) {
      notification.error({ message: error?.message || '删除角色失败' });
    }
  }

  // 获取角色详情并切入到表单Form
  async function viewDetail(userId: number) {
    try {
      const { code, data: userRecord, message: msg } = await getUser(userId);
      if (code === ResponseCode.Success) {
        formInstance.setFieldsValue({
          username: userRecord.username,
          nickname: userRecord.nickname,
          email: userRecord.email,
          roleIds: userRecord.roles.map((item) => item.id),
          avatarImage: userRecord.avatarImage,
        });
      } else {
        message.error(msg);
      }
    } catch (error: any) {
      console.log('UserManagement => index => getUser', '请求失败');
    }
  }

  // proTable 获取角色列表方法
  async function request(params: any) {
    try {
      const { code, data, message: msg } = await getUserList(params);
      if (code === ResponseCode.Success) {
        return {
          data: data.list,
          total: data.total,
        };
      }
      throw new Error(msg);
    } catch (error: any) {
      message.error(error?.message);
      return {
        data: [],
        total: 0,
      };
    }
  }

  // 弹窗点击确认，提交表单
  async function sureAddUser() {
    switch (modalConfig.type) {
      // 新增时
      case 'add': {
        // 获取表单数据
        const formData = await formInstance.validateFields();
        // 弹窗确认按钮loading
        setOperateLoadingLoading(true);
        try {
          const {
            code,
            data: newUserId,
            message: msg,
          } = await addUser(formData);
          if (code === ResponseCode.Success) {
            setModalConfig((config) => ({ ...config, visible: false }));
            actionRef.current?.reload();
            notification.success({
              message: `新增用户ID: ${newUserId}成功，密码是随机值，请登入邮箱修改密码`,
            });
          } else {
            notification.error({ message: msg || '新增用户失败' });
          }
        } catch (error: any) {
          notification.error({ message: error?.message || '新增用户失败' });
        }
        setOperateLoadingLoading(false);
        break;
      }
      // 修改时
      case 'edit': {
        const formData = await formInstance.validateFields();
        setOperateLoadingLoading(true);
        try {
          const { code, message: msg } = await updateUser(
            modalConfig.userId as number,
            formData,
          );
          if (code === ResponseCode.Success) {
            setModalConfig((config) => ({ ...config, visible: false }));
            actionRef.current?.reload();
            notification.success({ message: `更新用户成功` });
            // 如果是当前用户更新，重刷，优化用户体验逻辑
            if (modalConfig.userId === currentUser.id) {
              fetchUserInfo();
            }
          } else {
            notification.error({ message: msg || '更新用户失败' });
          }
        } catch (error: any) {
          notification.error({ message: error?.message || '更新用户失败' });
        }
        setOperateLoadingLoading(false);
        break;
      }
      // 查看时
      case 'view':
        setModalConfig((config) => ({ ...config, visible: false }));
        break;
    }
  }

  // 获取
  useEffect(() => {
    getRoleList({
      pageSize: Number.MAX_SAFE_INTEGER,
      current: 1,
    })
      .then(({ code, data }) => {
        if (code === ResponseCode.Success) {
          setRoleList(data.list);
        }
      })
      .catch(() => {
        console.log('UserManagement => index => getRoleList', '请求失败');
      });
  }, []);

  return (
    <PageContainer className="user-management">
      <ProTable<UserRecord>
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => {
          return request(params);
        }}
        scroll={{
          x: 1200,
        }}
        rowKey="id"
        search={{
          labelWidth: 100,
          defaultCollapsed: false,
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <Button
            key="add-detail"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              formInstance.resetFields();
              setModalConfig((config) => ({
                ...config,
                visible: true,
                type: 'add',
              }));
            }}
          >
            新增
          </Button>,
        ]}
      />
      <Modal
        title={MODAL_TITLE_MAP[modalConfig.type]}
        open={modalConfig.visible}
        onCancel={() =>
          setModalConfig((config) => ({
            ...config,
            visible: false,
            userId: undefined,
          }))
        }
        onOk={sureAddUser}
        confirmLoading={operateLoading}
      >
        <Form
          {...FormLayout}
          form={formInstance}
          disabled={modalConfig.type === 'view'}
        >
          <Form.Item name="username" label="账号" rules={DEFAULT_REQUIRED_RULE}>
            <Input />
          </Form.Item>
          <Form.Item name="email" label="邮箱" rules={DEFAULT_REQUIRED_RULE}>
            <Input />
          </Form.Item>
          <Form.Item name="nickname" label="昵称" rules={DEFAULT_REQUIRED_RULE}>
            <Input />
          </Form.Item>
          <Form.Item name="avatarImage" label="头像">
            <SingleUpload />
          </Form.Item>
          <Form.Item name="roleIds" label="角色管理">
            <Select mode="multiple" options={roleListOptions} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default UserManagement;
